package rabbitmq.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费者
 */

public class ConsumerDemo {
    public static void main(String[] args) throws IOException, TimeoutException {
        /**
         * 1.建立连接
         * 2.创建信道
         * 3.声明队列
         * 4.接收消息
         * 5.释放资源
         */

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("115.159.5.204");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setVirtualHost("/");
        //1.建立连接
        //2.创建信道
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        //3.声明队列
        channel.queueDeclare("hello",true,false,false,null);
        //4.接收消息
        Consumer consumer = new DefaultConsumer(channel){
            /**
             *
             * @param consumerTag the <i>consumer tag</i> associated with the consumer
             * @param envelope packaging data for the message
             * @param properties content header data for the message
             * @param body the message body (opaque, client-specific byte array)
             */
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body)
            {
                System.out.println("接收消息：" + new String(body));
            }
        };
        channel.basicConsume("hello",true,consumer);

        //5.释放资源
//        channel.close();
//        connection.close();
    }
}
